<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <!-- 根据 editKey 动态渲染不同的表单控件 -->
      <template v-if="editInfo.editKey === 'avatarUrl'">
        <van-uploader
            v-model="avatarFile"
            :after-read="afterRead"
            :max-count="1"
            :deletable="true"
        >
          <van-button icon="plus" type="primary">上传头像</van-button>
        </van-uploader>
      </template>

      <template v-else-if="editInfo.editKey === 'gender'">
        <van-radio-group v-model="editInfo.currentValue" direction="horizontal">
          <van-radio name="1">男</van-radio>
          <van-radio name="0">女</van-radio>
        </van-radio-group>
      </template>

      <template v-else>
        <van-field
            v-model="editInfo.currentValue"
            :name="editInfo.editKey"
            :label="editInfo.editName"
            :placeholder="`请输入${editInfo.editName}`"
            :rules="[{ required: true, message: `请填写${editInfo.editName}` }]"
        />
      </template>
    </van-cell-group>

    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        确认修改
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ref} from "vue";
import {useUserStore} from "../store/userStore.js";
import router from "../router/index.js";
import {showToast} from "vant";


const route = useRoute();

const userStore = useUserStore()
const user = userStore.userInfo
const editInfo = ref({
  editKey: route.query.editKey,
  editName: route.query.editName,
  currentValue: route.query.currentValue,
});

const avatarFile = ref([]);

const afterRead = (file) => {
  // 处理上传的图片文件
  console.log("上传的文件:", file);
  // 这里可以调用接口上传文件
};

const onSubmit = async (values) => {
  //设置请求对象
  switch (editInfo.value.editKey) {
    case "avatarUrl":
      user.avatarUrl = avatarFile.value[0].content;
      break;
    case "username":
      user.username = values.username
      break;

    case "phone":
      user.phone = values.phone

      break;
    case "email":
      user.email = values.email
      break;
    case "gender":
      user.gender = editInfo.value.currentValue; // 将用户选择的性别赋值给 user.gender
      break;
  }


  //发送更新请求
  const resp = await userStore.updateUser(user);
  console.log("resp", resp)
  if (resp.code === 200) {
    showToast("信息更新成功")

    router.back()
  }
};


</script>

<style scoped></style>